﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VirtualRouterClient.Properties;
using VirtualRouterClient.VirtualRouterService;
using Wpf_VirtualRouterPlus.Classes;
using Wpf_VirtualRouterPlus.Windows;

namespace Wpf_VirtualRouterPlus.UserControls
{
    /// <summary>
    /// Interaction logic for SettingsControl.xaml
    /// </summary>
    public partial class HotspotSettings : UserControl
    {
        // Os variable
        private bool isVirtualRouterRunning = false;
        private App myApp = (App)App.Current;


        Setting _setting;
        MainWindow _manager;

        public Setting Setting
        {
            get { return _setting; }
            set { _setting = value; }
        }
        public HotspotSettings(MainWindow manager_)
        {
            InitializeComponent();

            _manager = manager_;
            _setting = _manager.Setting;

            _initializeSettingInOs(); 

            Loaded += new RoutedEventHandler(HotspotSettings_Loaded);
        }

        private void HotspotSettings_Loaded(object sender, RoutedEventArgs e)
        {
            _initialize();

        }

        private void _initialize()
        {
            _initializeControls();

            
        }

        private void _initializeSettingInOs()
        {
            txtbHotspotName.Text = Settings.Default.SSID;
            txtbPassword.Text = Settings.Default.Password;
        }

        private void _initializeControls()
        {
            cbStartUp.IsChecked = _setting.StartWithWindow;

            // init max peers
            ConnectionSettings connectionSettings = myApp.VirtualRouter.GetConnectionSettings();
            txtbMaxPeers.Text = connectionSettings.MaxPeerCount.ToString() ;
        }

        private void btnOption_Click(object sender, RoutedEventArgs e)
        {
            OptionWindow optionWindow = new OptionWindow(this);
            optionWindow.ShowDialog();
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            //AboutWindow aboutWindow = new AboutWindow();
            //aboutWindow.ShowDialog();
            MainWindow.ShowAboutBox();

        }

        private void cbStartUp_Checked(object sender, RoutedEventArgs e)
        {
            _setting.StartWithWindow = (bool)cbStartUp.IsChecked;
            _setting.applySettings();
            _setting.saveSettings();
        }

        private void cbStartUp_Unchecked(object sender, RoutedEventArgs e)
        {
            _setting.StartWithWindow = (bool)cbStartUp.IsChecked;
            _setting.applySettings();
            _setting.saveSettings();
        }

        internal void reload()
        {
            _initialize();
        }

        private void btnShowPassword_Click(object sender, RoutedEventArgs e)
        {
            bool currentState = (gTextBox.Visibility == System.Windows.Visibility.Visible);
            bool nextState = !currentState;
            _showPassword(nextState);
        }

        private void _showPassword(bool show)
        {
            if (show)
            {
                gTextBox.Visibility = System.Windows.Visibility.Visible;
                gPasswordBox.Visibility = System.Windows.Visibility.Collapsed;
                btnShowPassword.Content = FindResource("btnShowPassword_Hide");
            }
            else
            {
                gTextBox.Visibility = System.Windows.Visibility.Collapsed;
                gPasswordBox.Visibility = System.Windows.Visibility.Visible;
                btnShowPassword.Content = FindResource("btnShowPassword_Show");
            }
        }

        private void pwbPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            txtbPassword.Text = pwbPassword.Password;
        }

        private void txtbMaxPeers_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("^[0-9]+");
            bool match1 = regex.IsMatch(e.Text);
            if (!match1)
            {
                e.Handled = true;
                return;
            }
            TextBox textbox = sender as TextBox;
            String newText = textbox.Text + e.Text;
            int num = int.Parse(newText);
            bool match2 = (num > 0&&num<=32);
            e.Handled = !(match2);
        }

        #region Os region

        internal void updateDisplay()
        {

            UpdateUIDisplay();

            RefreshSharableConnectionsDisplay();

            _manager.callBack_UpdatePeers();
        }


        private void UpdateUIDisplay()
        {
            var enableToggleButton = false;
            var enableSettingsFields = false;

            if (myApp.IsVirtualRouterServiceConnected)
            {
                enableToggleButton = true;
                try
                {
                    btnStart.IsEnabled = true;
                    if (myApp.VirtualRouter.IsStarted())
                    {
                        enableSettingsFields = false;
                        //btnStart.Content = FindResource("btnStart_Stop");
                        btnStart.SetResourceReference(Button.ContentProperty, "btnStart_Stop");

                        _manager.TrayIcon.Text = "Virtual Router (Running)";
                        _manager.TrayIcon.Icon = new System.Drawing.Icon(
                            Application.GetResourceStream(new Uri("icons/virtualrouterenabled.ico", UriKind.Relative)).Stream
                            );

                        if (!isVirtualRouterRunning)
                        {
                            //x this.Icon = this.imgIcon.Source = BitmapFrame.Create(Application.GetResourceStream(new Uri("Icons/VirtualRouterEnabled.ico", UriKind.Relative)).Stream);
                            _manager.Icon = BitmapFrame.Create(Application.GetResourceStream(new Uri("Icons/VirtualRouterEnabled.ico", UriKind.Relative)).Stream);
                        }
                        isVirtualRouterRunning = true;

                        txtbHotspotName.Text = myApp.VirtualRouter.GetConnectionSettings().SSID;
                        txtbPassword.Text = myApp.VirtualRouter.GetPassword();
                        pwbPassword.Password = txtbPassword.Text;
                    }
                    else
                    {
                        enableSettingsFields = true;
                        //btnStart.Content = "Start Virtual Router";
                        btnStart.SetResourceReference(Button.ContentProperty, "btnStart_Start");

                        _manager.setStatus("Virtual Router Stopped...");

                        _manager.TrayIcon.Text = "Virtual Router (Stopped)";
                        _manager.TrayIcon.Icon = new System.Drawing.Icon(
                            Application.GetResourceStream(new Uri("icons/virtualrouterdisabled.ico", UriKind.Relative)).Stream
                            );

                        if (isVirtualRouterRunning)
                        {
                            //this.Icon = this.imgIcon.Source = BitmapFrame.Create(Application.GetResourceStream(new Uri("Icons/VirtualRouterDisabled.ico", UriKind.Relative)).Stream);
                            _manager.Icon = BitmapFrame.Create(Application.GetResourceStream(new Uri("Icons/VirtualRouterDisabled.ico", UriKind.Relative)).Stream);
                        }
                        isVirtualRouterRunning = false;
                    }
                }
                catch
                {
                    enableToggleButton = false;
                    enableSettingsFields = false;
                }
            }

            btnStart.IsEnabled = enableToggleButton;

            // Enable/diable settings Settings
            //gbSettings.IsEnabled = enableSettingsFields;
            txtbHotspotName.IsEnabled = enableSettingsFields;
            txtbPassword.IsEnabled = enableSettingsFields;
            pwbPassword.IsEnabled = enableSettingsFields;
            gbAdvanceSettings.IsEnabled = enableSettingsFields;
        }

        private void RefreshSharableConnectionsDisplay()
        {
            if (myApp.IsVirtualRouterServiceConnected)
            {
                cbbInternetToShare.DisplayMemberPath = "Name";

                var connections = myApp.VirtualRouter.GetSharableConnections();

                Guid selectedId = Guid.Empty;
                if (myApp.VirtualRouter.IsStarted())
                {
                    var sharedConn = myApp.VirtualRouter.GetSharedConnection();
                    if (sharedConn != null)
                    {
                        selectedId = sharedConn.Guid;
                    }
                }
                else
                {
                    var previousItem = cbbInternetToShare.SelectedItem as SharableConnection;
                    if (previousItem != null)
                    {
                        selectedId = previousItem.Guid;
                    }
                }

                cbbInternetToShare.Items.Clear();
                foreach (var c in connections)
                {
                    cbbInternetToShare.Items.Add(c);
                    if (c.Guid == selectedId)
                    {
                        cbbInternetToShare.SelectedItem = c;
                    }
                }
            }
        }



        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (myApp.IsVirtualRouterServiceConnected)
            {
                if (myApp.VirtualRouter.IsStarted())
                {
                    myApp.VirtualRouter.Stop();
                }
                else
                {
                    if (this.ValidateFields())
                    {
                        // init for setting with max peer
                        String sMaxPeers = txtbMaxPeers.Text;
                        int maxPeers = 32;
                        if(!String.IsNullOrEmpty(sMaxPeers))
                            maxPeers = int.Parse(sMaxPeers);


                        bool result = myApp.VirtualRouter.SetConnectionSettings(txtbHotspotName.Text, maxPeers);
                        myApp.VirtualRouter.SetPassword(txtbPassword.Text);

                        if (!myApp.VirtualRouter.Start((SharableConnection)cbbInternetToShare.SelectedItem))
                        {
                            string strMessage = myApp.VirtualRouter.GetLastError() ?? "Virtual Router Could Not Be Started!";
                            _manager.setStatus(strMessage);

                            MessageBox.Show(strMessage, FindResource("MainWindow_Title").ToString());
                        }
                        else
                        {
                            _manager.setStatus("Virtual Router Started...");
                        }

                    }
                }
            }

            UpdateUIDisplay();
        }

        private bool ValidateFields()
        {
            var errorMessage = string.Empty;

            if (txtbHotspotName.Text.Length <= 0)
            {
                errorMessage += FindResource("errorMsg_HotspotNameEmpty") + Environment.NewLine;//"Hotspot Name (SSID) is required."
            }

            if (txtbHotspotName.Text.Length > 32)
            {
                errorMessage += FindResource("errorMsg_HotspotName_Error32") + Environment.NewLine; //"Hotspot Name (SSID) can not be longer than 32 characters."
            }

            if (txtbPassword.Text.Length < 8)
            {
                errorMessage += FindResource("errorMsg_Pass_Error8") + Environment.NewLine;//"Password must be at least 8 characters."
            }

            if (txtbPassword.Text.Length > 64)
            {
                errorMessage += FindResource("errorMsg_Pass_Error64") + Environment.NewLine;//"Password can not be longer than 64 characters."
            }

            if (!string.IsNullOrEmpty(errorMessage))
            {
                MessageBox.Show(errorMessage, "", MessageBoxButton.OK, MessageBoxImage.Warning);
                return false;
            }

            return true;
        }


        private void btnRefreshInternetToShare_Click(object sender, RoutedEventArgs e)
        {
            RefreshSharableConnectionsDisplay();
        }

        #endregion









    }
}
